import 'package:flutter/material.dart';

class SearchBarView extends StatefulWidget {
  @override
  _SearchBarViewState createState() => _SearchBarViewState();
}

class _SearchBarViewState extends State<SearchBarView> {
  bool _isShowClear = false;

  TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    _controller.addListener(() {
      setState(() {
        _controller.text.isEmpty ? _isShowClear = false : _isShowClear = true;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      margin: EdgeInsets.all(10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: Colors.grey, width: 1)),
      child: Stack(
        alignment: AlignmentDirectional.centerEnd,
        children: [
          Row(
            children: [
              Padding(
                padding: EdgeInsets.only(left: 10),
              ),
              Icon(
                Icons.search,
                color: Colors.grey,
                size: 20,
              ),
              Padding(
                padding: EdgeInsets.only(left: 10),
              ),
              Expanded(
                child: TextField(
                  maxLines: 1,
                  cursorColor: Colors.grey,
                  // 光标颜色
                  style: TextStyle(
                    color: Colors.black,
                  ),
                  decoration: InputDecoration(
                    contentPadding: EdgeInsets.only(top: -12),
                    border: InputBorder.none,
                    hintText: "请输入搜索内容",
                    hintStyle: TextStyle(color: Colors.grey),
                  ),
                  controller: _controller,
                ),
              )
            ],
          ),
          Visibility(
            visible: _isShowClear,
            child: InkWell(
              onTap: () {
                _controller.clear();
              },
              child: Container(
                margin: EdgeInsets.only(right: 6),
                child: Icon(
                  Icons.cancel,
                  color: Colors.grey,
                  size: 20,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
